package l1j.server.server.clientpackets;

import l1j.opqlo.Server.L1World.L1World;
import l1j.opqlo.Server.L1World.WorldClan;
import l1j.server.echo.ClientThread;
import l1j.server.server.datatables.CastleTable;
import l1j.server.server.datatables.ItemTable;
import l1j.server.server.model.L1Clan;
import l1j.server.server.model.L1Inventory;
import l1j.server.server.model.Instance.L1ItemInstance;
import l1j.server.server.model.Instance.L1PcInstance;
import l1j.server.server.model.item.L1ItemId;
import l1j.server.server.serverpackets.S_ServerMessage;
import l1j.server.server.templates.L1Castle;

import java.util.logging.Level;
import java.util.logging.Logger;
// Referenced classes of package l1j.server.server.clientpackets:
// ClientBasePacket

/**
 * TODO: 處理收到由客戶端傳來取得城堡稅收的封包(?)
 */
public class C_Drawal extends ClientBasePacket {

	private static final String C_DRAWAL = "[C] C_Drawal";
	private static final Logger _log = Logger.getLogger(C_Drawal.class.getName());
	@Override
	public String getType() {
		return C_DRAWAL;
	}

	@Override
	public void start(final byte[] decrypt, final ClientThread client) {
		try {
			// 資料載入
			this.read(decrypt);

			final L1PcInstance pc = client.getActiveChar();
			if (pc == null) {
				return;
			}

			this.readD();
			final int j = Math.abs(this.readD());

			final L1Clan clan = WorldClan.get().getClan(pc.getClanname());
			if (clan != null) {
				final int castle_id = clan.getCastleId();
				if (castle_id != 0) {
					final L1Castle l1castle = CastleTable.getInstance().getCastleTable(castle_id);
					int money = l1castle.getPublicMoney();
					money -= j;
					final L1ItemInstance item = ItemTable.getInstance().createItem(L1ItemId.ADENA);
					if (item != null) {
						l1castle.setPublicMoney(money);
						CastleTable.getInstance().updateCastle(l1castle);
						if (pc.getInventory().checkAddItem(item, j) == L1Inventory.OK) {
							pc.getInventory().storeItem(L1ItemId.ADENA, j);
						}
						else {
							L1World.getInstance().getInventory(pc.getX(), pc.getY(), pc.getMapId()).storeItem(L1ItemId.ADENA, j);
						}
						pc.sendPackets(new S_ServerMessage(143, "$457", "$4" + " (" + j + ")")); // \f1%0%s
						// 給你
						// %1%o
						// 。
					}
				}
			}
		} catch (final Exception e) {
			_log.log(Level.SEVERE, e.getLocalizedMessage(), e);

		} finally {
			this.over();
		}
	}

}
